package cn.proandcus;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

/**
 * 新的生产者 消费者 模式
 */
@Slf4j
public class New {
    public static void main(String[] args) {
        MessageQueue queue=new MessageQueue(5);
        for (int i = 0; i <3 ; i++) {
            int j=i;
            new Thread(()->{
                while (true) {
                    try {
                        queue.take(new Message(j, "我的值" + j));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"生产者"+i).start();
        }
        new Thread(()->{
            try {
                while (true) {
                    //Thread.sleep(1000);
                    Message message = queue.get();

                   // System.out.println("消费者消费" + message.toString());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"消费者").start();
    }
}
@Slf4j
class MessageQueue{
    private LinkedList<Message> linkedList=new LinkedList<>();
    private int linkMax;//最大容量
    public MessageQueue(int linkMax){
        this.linkMax=linkMax;
    }
    //存消息
    public  void  take(Message message) throws InterruptedException {
           synchronized (linkedList) {
               while (linkedList.size()== linkMax) {//link 队列满 等待
                   log.info("队列满了");
                   try {
                       linkedList.wait();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               Thread.sleep(3000);//生产时间
               linkedList.addLast(message);//尾插
               log.info("生产一个");
               linkedList.notifyAll();//唤醒其他线程
           }
    }
    //取消息
    public  Message get() throws InterruptedException {
             synchronized (linkedList) {
                 while(linkedList.isEmpty()) {
                     log.info("队列空了 等生产");
                     linkedList.wait();
                 }
                 Message messages = linkedList.removeFirst();
                 linkedList.notifyAll();
                 log.info("消费中");
                 return messages;//取出第一个
             }
    }
}
final class Message{
    private int id;//id标识
    private Object value; //值
    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    public int getId() {
        return id;
    }

    public Object getValue() {
        return value;
    }
}
